<template>
  <div class="comment-view">
    <u-comment-scroll :disable="disable" @more="more">
      <u-comment
        ref="commentRef"
        :config="configs"
        :show-size="2"
        page
        style="display: flex; flex-direction: column"
        relative-time
        @submit="submit"
        @like="like"
        @reply-page="replyPage"
        @show-info="showInfo"
        @mention-search="mentionSearch"
        @remove="remove"
      >
        <!-- <template #list-title>全部评论</template> -->
        <template #card="scope">
          <div class="user-card">
            <div class="user-avatar">
              <el-avatar style="margin-top: 5px" :size="40" fit="cover" :src="scope.avatar">
                <img src="https://cube.elemecdn.com/e/fd/0fc7d20532fdaf769a25683617711png.png" />
              </el-avatar>
            </div>
            <div class="user-content">
              <div class="user-info">
                <a href="" class="username" target="_blank">
                  <span class="name" style="max-width: 10em">{{ scope.username }}</span>
                  <span blank="true" class="rank">
                    <u-icon v-dompurify-html="useLevel(scope.level)" size="24" />
                  </span>
                </a>
              </div>
              <div class="social-info">
                <a href="" class="attention">
                  <span>{{ scope.attention }}</span>
                  <span>关注</span>
                </a>
                <a href="" class="follower">
                  <span>{{ scope.follower }}</span>
                  <span>粉丝</span>
                </a>
                <a href="" class="like">
                  <span>{{ scope.like }}</span>
                  <span>获赞</span>
                </a>
              </div>
              <div class="card-btn">
                <el-button type="primary">关注</el-button>
                <el-button>发消息</el-button>
              </div>
            </div>
          </div>
        </template>
        <template #operate="scope">
          <my-operate :comment="scope" @remove="remove" />
        </template>
        <u-comment-nav v-model="latest" @sorted="sorted" />
      </u-comment>
    </u-comment-scroll>
  </div>
</template>

<script setup lang="ts">
import { reactive, ref, onMounted } from 'vue';
import {
  UToast,
  ConfigApi,
  CommentApi,
  useLevel,
  CommentReplyPageApi,
  cloneDeep,
  usePage,
  CommentSubmitApi,
  throttle,
  CommentInstance
} from 'undraw-ui';
// 下载表情包资源emoji.zip https://gitee.com/undraw/undraw-ui/releases
// static文件放在public下,引入emoji.ts文件可以移动到自定义位置
import emoji from '@/assets/emoji';
import { UComment, UIcon, UCommentNav } from 'undraw-ui';
import { pageComment, saveComment, pageReply } from '@/api/comment';
import { getCommentLikedById, liked } from '@/api/commentLike';
import MyOperate from './component/operate.vue';
import { useUserStore } from '@/store/modules/user';
import { useCommentStore } from '@/store/modules/comment';

const userStore = useUserStore();
const commentStore = useCommentStore();

defineOptions({ name: 'Comment' });
const props = defineProps({
  blogId: {
    type: String,
    default: null
  }
});

const userArr = [
  {
    id: 1,
    name: '张三',
    avatar: 'https://cube.elemecdn.com/0/88/03b0d39583f48206768a7534e55bcpng.png'
  },
  {
    id: 2,
    name: '李四',
    avatar: 'https://cube.elemecdn.com/9/c2/f0ee8a3c7c9638a54940382568c9dpng.png'
  }
];

// 评论用户的详细信息
const configs = reactive<ConfigApi>({
  user: {
    ...userStore.userInfo,
    // 评论id数组 建议:存储方式用户id和文章id和评论id组成关系,根据用户id和文章id来获取对应点赞评论id,然后加入到数组中返回
    likeIds: []
  },
  emoji,
  comments: [],
  relativeTime: true, // 开启人性化时间
  page: true, // 开启分页
  mention: {
    // 开启提交功能
    data: userArr,
    alias: { username: 'name' },
    showAvatar: true
  }
  // showLevel: false,
  // showHomeLink: false,
  // showAddress: false,
  // showLikes: false
});

// 提及@ 事件
const mentionSearch = (val: string) => {
  configs.mention!.data = userArr.filter(v => v.name.includes(val));
};
onMounted(() => {
  getComments(pageData.pageNum, pageData.pageSize);
  getLikes();
});

// 获取评论列表
const getComments = async (pageNum, pageSize) => {
  const res = await pageComment({
    pageNum,
    pageSize,
    blogId: props.blogId
  });
  const data = res.data.list.map(item => ({
    ...item,
    articleId: item.blogId
  }));
  configs.comments.push(...data);
  pageData.total = res.data.list.length;
  return res.data;
};
// 获取点赞信息
const getLikes = async () => {
  getCommentLikedById(userStore.userInfo.id).then(res => {
    configs.user.likeIds = res.data;
  });
};

// 排序
const latest = ref(true);
const sorted = (latest: boolean) => {
  console.log(latest);
};

// 是否禁用滚动加载评论
const disable = ref(false);
const pageData = reactive({
  // 当前页数
  pageNum: 1,
  // 页大小
  pageSize: 3,
  // 评论总数量
  total: 30
});
// 加载更多评论
const more = () => {
  if (pageData.pageNum <= Math.ceil(pageData.total / pageData.pageSize)) {
    pageData.pageSize = pageData.pageSize + 3;
    setTimeout(async () => {
      const comments = await getComments(pageData.pageNum, pageData.pageSize);
      configs.comments.push(...comments);
    }, 200);
  } else {
    disable.value = true;
  }
};
// 用户信息是否加载
const loading = ref(false);
// 请求获取用户详细信息
const showInfo = (uid: string, finish: Function) => {
  console.log(loading.value);
  loading.value = true;
  console.log(`获取用户信息: ${uid}`);

  commentStore.getCommenterInfo(Number(uid)).then(res => {
    const userInfo = {
      id: res.userId,
      username: res.username,
      avatar: res.avatar,
      level: res.level,
      like: res.like,
      attention: res.attention,
      follower: res.follower
    };
    loading.value = false;
    finish(userInfo);
  });
};
function toFormData(object: any) {
  const formData = new FormData();
  Object.keys(object).forEach(key => {
    const value = object[key];
    if (Array.isArray(value)) {
      value.forEach((subValue, i) => formData.append(`${key}[${i}]`, subValue));
    } else {
      formData.append(key, object[key]);
    }
  });
  return formData;
}

/**
 * 去除属性值为 null和undefined、''的数据
 * @param obj
 */
function removeEmptyField(obj: any) {
  return Object.keys(obj)
    .filter(key => obj[key] !== null && obj[key] !== undefined && obj[key] !== '')
    .reduce(
      (acc, key) => ({
        ...acc,
        [key]: obj[key]
      }),
      {}
    );
}

// 提交评论事件
const submit = ({ content, parentId, finish }: CommentSubmitApi) => {
  console.log(`提交评论: ${content}`, parentId);
  const formData = {
    blogId: props.blogId,
    content,
    parentId
  };
  saveComment(toFormData(removeEmptyField(formData))).then(res => {
    finish(res.data as any);
    UToast({
      message: '评论成功!',
      type: 'info'
    });
  });

  // saveBlogComment(formData as CommentSave).then((res: any) => {
  //   finish(res.data as any)
  //   UToast({ message: '评论成功!', type: 'info' })
  //   // pageData.value = data.list;
  //   // total.value = data.total;
  // })
  // .finally(() => {
  //   loading.value = false;
  // });
};

// 删除评论
// const remove = (id: string, finish: () => void) => {
//   console.log('删除评论: ' + id);
//   setTimeout(() => {
//     finish();
//     alert(`删除成功: ${id}`);
//   }, 200);
// };

const commentRef = ref<CommentInstance>();

// 删除评论
const remove = (comment: CommentApi) => {
  setTimeout(() => {
    commentRef.value?.remove(comment);
  }, 200);
};

// // 操作按钮事件
// const operate = (type: string, comment: CommentApi, finish: Function) => {
//   console.log('操作按钮事件', type, comment)
//   _throttle(type, comment, finish)
// }

// // 防抖
// const _throttle = throttle((type: string, comment: CommentApi, finish: Function) => {
//   if (type === '删除') {
//     alert(`删除成功dddd: ${comment.id}`)
//     finish()
//   } else if (type === '举报') {
//     alert(`举报成功ssss: ${comment.id}`)
//   }
// })

// // 举报用户
// const report = (id: string, finish: () => void) => {
//   console.log('举报用户: ' + id)
//   setTimeout(() => {
//     finish()
//     alert(`举报成功: ${id}`)
//   }, 200)
// }

// 点赞按钮事件
const like = (id: string, finish: () => void) => {
  console.log(`点赞: ${id}`);
  liked({
    uid: userStore.userInfo.id,
    commentId: id
  }).then(res => {
    finish();
  });
};

// 回复分页
const replyPage = ({ parentId, pageNum, pageSize, finish }: CommentReplyPageApi) => {
  console.log(pageNum, pageSize);
  // 根据 parentId查询后端分页回复列表返回并覆盖回复
  pageReply({
    url: `/${pageNum}/${pageSize}`,
    parentId
  }).then(res => {
    // 模拟请求接口分页 请求覆盖评论对应的回复数据(全量覆盖回复数据)
    const reply = cloneDeep(res.data);
    if (reply) {
      const tmp = {
        total: reply?.total,
        // 分页提取回复
        list: usePage(pageNum, pageSize, reply.list)
      };
      setTimeout(() => {
        finish(tmp);
      }, 200);
    }
  });
};
</script>

<style lang="scss" scoped>
.user-card {
  display: flex;
  .user-content {
    flex: 1;
    margin-left: 16px;
    .user-info {
      .username {
        display: flex;
        align-items: center;
        text-decoration: none;
        .name {
          max-width: 10rem;
          font-weight: 500;
          font-size: 15px;
          color: #252933;
          line-height: 32px;
          margin-right: 4px;
        }
      }
    }
    .social-info {
      margin-bottom: 10px;
      a {
        text-decoration: none;
      }
      a:not(:first-child) {
        margin-left: 18px;
      }
      a span:last-child {
        margin-left: 3px;
        color: #9499a0;
      }
    }
  }
}
</style>
